import time
import re
import json
import urllib
import scrapy
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
import math
import base64
from urllib.parse import urlencode


class spider(BaseTaxPolicySpider):
    name = "fuxin_lnsfxsqhqrmzf"

    province: str = "辽宁省"  # 取表格
    city: str = "阜新市"  # 取表格
    county: str = "清河门区"  # 取表格
    park: str = "None"  # 取表格
    source: str = "辽宁省阜新市清河门区人民政府"  # 取表格 同一个来源合并
    url: str = "https://www.fxtp.gov.cn/newslistex.thtml?id=15609"  # 注明入口网址，以便后续排错
    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
        'Sec-Fetch-Dest': 'document',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-Site': 'none',
        'Sec-Fetch-User': '?1',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
        'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"'
    }
    url_list = [
        ["https://www.fxqhm.gov.cn/newslistex.thtml?id=14212&pn=1", "辽宁省阜新市清河门区人民政府"],
        ["https://www.fxqhm.gov.cn/newslistex.thtml?id=14213&pn=1", "辽宁省阜新市清河门区人民政府"],
    ]

    def start_requests(self):
        for url in self.url_list:

            # 发送GET请求
            yield scrapy.Request(url=url[0], method='GET', headers=self.headers, callback=self.detail_requests, meta={'source': url[1]})

    def detail_requests(self, response, **kwargs):
        page = response.meta.get('page', "")
        links = response.xpath("//div[@class='list1-ul-link-inner']/a/@href").getall()  # 取链接
        title_list = response.xpath("//div[@class='list1-ul-link-inner']/a/text()").getall()  # 取标题
        pub_date = response.xpath("//div[@class='list1-ul-link']//div[@class='tabs2Right-part2']/text()").getall()  # 取标题
        print("links", links, page)
        print("pub_date", pub_date, page)
        print("title_list", title_list, page)
        if len(title_list) == len(links) and len(pub_date) == len(title_list):
            for i in range(len(links)):
                if 'http' not in links[i]:
                    if links[i].count(".") == 5:
                        links[i] = f"https://{links[i][5:]}"
                    if links[i].count(".") == 1:
                        links[i] = f"https://{links[i]}"
                print("links[i]", links[i], 'page', page)
                yield scrapy.Request(links[i], callback=self.parse_detail, meta={'pubdate': pub_date[i],
                                                                                 'title': title_list[i], "source": response.meta.get('source')})
        else:
            raise ("出错了", page)

        # 翻页逻辑
        if response.meta.get("is_next") is not False:
            pattern = r"""(\d+)页"""
            match = re.search(pattern, response.text)
            pages = int(match.group(1))
            if pages >= 1:
                print("总页数：", pages)
                for page in range(2, pages + 1):
                    print("当前页：", page)
                    not_first_url = response.url[:-1] + str(page)
                    # 设置请求头

                    # 发送请求
                    yield scrapy.Request(url=not_first_url, method='GET', headers=self.headers,
                                         callback=self.detail_requests, meta={'is_next': False, 'page': page, "source": response.meta.get('source')})

    def parse_list(self, response, **kwargs):
        pass

    def parse_detail(self, response, **kwargs):
        item = Item()
        title = response.meta.get('title')
        pub_date = response.meta.get('pubdate')
        if 'pdf' in response.url or 'doc' in response.url or 'xls' in response.url or 'jpg' in response.url:
            print("特殊url：", response.url)
            content = response.url

        else:
            content = response.xpath(".").get()
        item['title'] = title
        item['source_url'] = response.url
        item['publish_date'] = pub_date
        item['content'] = content
        item['source'] = response.meta.get('source')
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        if '已失效' in item['title'] or '已废止' in item['title'] or '已修改' in item['title'] or '废止' in item['title'] or '失效' in item['title']:
            item['state'] = '0'
        else:
            item['state'] = None
        # print("item", item)
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl fuxin_lnsfxsqhqrmzf".split())
